package feces.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.Getter;
import feces.model.User;

/**
 * 用户身份校验过滤器
 *
 * @author Bromine0x23
 */
@WebFilter(filterName = "login_filter", urlPatterns = { "*.html", "*.jsp", "/api/*" })
public class LoginFilter implements Filter {

	public static final String KEY_USER = "user";
	
	public static final String URL_LOGIN = "/login.html";
	
	public static final String URL_API_LOGIN = "/login";
	
	@Getter
	public String prefix;
	
	@Override
	public void init(
		FilterConfig config
	) throws ServletException {
		prefix = config.getServletContext().getContextPath();
	}

	@Override
	public void doFilter(
		ServletRequest request,
		ServletResponse response,
		FilterChain chain
	) throws IOException, ServletException {
		if (request instanceof HttpServletRequest) {
			HttpServletRequest http_request = (HttpServletRequest) request;
			String request_uri = http_request.getRequestURI();
			String uri = request_uri.substring(getPrefix().length());
			if (!(uri.equals(URL_LOGIN) || uri.equals(URL_API_LOGIN))) {
				User user = (User) http_request.getSession().getAttribute(KEY_USER);
				if (user == null) {
					((HttpServletResponse) response).sendRedirect(getPrefix() + URL_LOGIN);
					return;
				}
			}
			chain.doFilter(request, response);
		}
	}
	
	@Override
	public void destroy(
	) {
		// do nothing
	}

}
